{% extends "base.html" %}

{% block content %}
<div class="row justify-content-center">
    <div class="col-lg-10">
        <!-- 导航栏 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div class="d-flex align-items-center">
                <a href="javascript:history.back()" class="btn btn-outline-secondary me-3">
                    <i class="bi bi-arrow-left me-1"></i>返回
                </a>
                <h2 class="mb-0">
                    <i class="bi bi-envelope-open me-2"></i>邮件详情
                </h2>
            </div>
            
            <div class="btn-group">
                {% if email.recipient_id == current_user.id and not email.is_read %}
                    <button class="btn btn-outline-primary" onclick="markAsRead({{ email.id }})">
                        <i class="bi bi-check me-1"></i>标记已读
                    </button>
                {% endif %}
                
                {% if email.sender_id == current_user.id %}
                    <a href="{{ url_for('main.compose') }}?reply_to={{ email.id }}" 
                       class="btn btn-outline-success">
                        <i class="bi bi-reply me-1"></i>转发
                    </a>
                {% else %}
                    <a href="{{ url_for('main.compose') }}?reply_to={{ email.id }}" 
                       class="btn btn-outline-success">
                        <i class="bi bi-reply me-1"></i>回复
                    </a>
                {% endif %}
                
                <button class="btn btn-outline-danger" onclick="deleteEmail({{ email.id }})">
                    <i class="bi bi-trash me-1"></i>删除
                </button>
            </div>
        </div>

        <!-- 邮件内容 -->
        <div class="card">
            <!-- 邮件头部信息 -->
            <div class="card-header">
                <div class="row">
                    <div class="col-md-8">
                            <h4 class="mb-3">{{ email.subject|e }}</h4>
                        
                        <div class="email-meta">
                            <div class="row mb-2">
                                <div class="col-sm-2">
                                    <strong>发件人：</strong>
                                </div>
                                <div class="col-sm-10">
                                    <div class="d-flex align-items-center">
                                        <i class="bi bi-person-circle me-2 text-primary"></i>
                                        <div>
                                            <strong>{{ email.sender.username|e }}</strong>
                                            {% if email.sender.real_name %}
                                                <span class="text-success ms-2">({{ email.sender.real_name|e }})</span>
                                            {% endif %}
                                            <br>
                                            <small class="text-muted">{{ email.sender.email|e }}</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row mb-2">
                                <div class="col-sm-2">
                                    <strong>收件人：</strong>
                                </div>
                                <div class="col-sm-10">
                                    <div class="d-flex align-items-center">
                                        <i class="bi bi-person-circle me-2 text-success"></i>
                                        <div>
                                            <strong>{{ email.recipient.username|e }}</strong>
                                            {% if email.recipient.real_name %}
                                                <span class="text-success ms-2">({{ email.recipient.real_name|e }})</span>
                                            {% endif %}
                                            <br>
                                            <small class="text-muted">{{ email.recipient.email|e }}</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-sm-2">
                                    <strong>时间：</strong>
                                </div>
                                <div class="col-sm-10">
                                    <i class="bi bi-clock me-2 text-muted"></i>
                                    {{ email.sent_at.strftime('%Y年%m月%d日 %H:%M:%S') }}
                                    <small class="text-muted ms-2">
                                        ({{ email.sent_at.strftime('%A') }})
                                    </small>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-4 text-end">
                        <!-- 邮件状态 -->
                        <div class="mb-3">
                            {% if email.is_read %}
                                <span class="badge bg-success">
                                    <i class="bi bi-envelope-open me-1"></i>已读
                                </span>
                            {% else %}
                                <span class="badge bg-primary">
                                    <i class="bi bi-envelope me-1"></i>未读
                                </span>
                            {% endif %}
                            
                            {% if email.sender_id == current_user.id %}
                                <span class="badge bg-info">
                                    <i class="bi bi-send me-1"></i>已发送
                                </span>
                            {% else %}
                                <span class="badge bg-secondary">
                                    <i class="bi bi-inbox me-1"></i>收件箱
                                </span>
                            {% endif %}
                        </div>
                        
                        <!-- 快速操作 -->
                        <div class="btn-group-vertical btn-group-sm">
                            <button class="btn btn-outline-secondary" onclick="printEmail()" title="打印">
                                <i class="bi bi-printer"></i>
                            </button>
                            <button class="btn btn-outline-secondary" onclick="exportEmail()" title="导出">
                                <i class="bi bi-download"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 邮件正文 -->
            <div class="card-body">
                <div class="email-content">
                    <div class="content-wrapper p-4 bg-light rounded">
                        <div style="white-space: pre-wrap; line-height: 1.6; font-size: 14px;">{{ email.content|e }}</div>
                    </div>
                </div>
            </div>
            
            <!-- 邮件操作 -->
            <div class="card-footer">
                <div class="d-flex justify-content-between align-items-center">
                    <div class="text-muted">
                        <small>
                            <i class="bi bi-info-circle me-1"></i>
                            邮件ID: {{ email.id }} | 
                            字符数: {{ email.content|length }}
                        </small>
                    </div>
                    
                    <div class="btn-group">
                        {% if email.sender_id != current_user.id %}
                            <a href="{{ url_for('main.compose') }}?reply_to={{ email.id }}" 
                               class="btn btn-primary">
                                <i class="bi bi-reply me-1"></i>回复
                            </a>
                        {% endif %}
                        
                        <a href="{{ url_for('main.compose') }}?forward={{ email.id }}" 
                           class="btn btn-outline-primary">
                            <i class="bi bi-arrow-right me-1"></i>转发
                        </a>
                        
                        <button class="btn btn-outline-danger" onclick="deleteEmail({{ email.id }})">
                            <i class="bi bi-trash me-1"></i>删除
                        </button>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 相关邮件 -->
        {% if related_emails %}
        <div class="card mt-4">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="bi bi-collection me-2"></i>相关邮件
                </h5>
            </div>
            <div class="card-body">
                <div class="list-group list-group-flush">
                    {% for related in related_emails %}
                        <div class="list-group-item">
                            <div class="d-flex justify-content-between align-items-start">
                                <div class="flex-grow-1">
                                    <h6 class="mb-1">
                                        <a href="{{ url_for('main.view_email', email_id=related.id) }}" 
                                           class="text-decoration-none">
                                            {{ related.subject|e }}
                                        </a>
                                    </h6>
                                    <p class="mb-1 text-muted">
                                        {% if related.sender_id == current_user.id %}
                                            发送给: {{ related.recipient.username|e }}
                                        {% else %}
                                            来自: {{ related.sender.username|e }}
                                        {% endif %}
                                    </p>
                                    <small class="text-muted">
                                        {{ related.sent_at.strftime('%Y-%m-%d %H:%M') }}
                                    </small>
                                </div>
                                <div>
                                    {% if related.is_read %}
                                        <i class="bi bi-envelope-open text-muted"></i>
                                    {% else %}
                                        <i class="bi bi-envelope-fill text-primary"></i>
                                    {% endif %}
                                </div>
                            </div>
                        </div>
                    {% endfor %}
                </div>
            </div>
        </div>
        {% endif %}
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 标记为已读
async function markAsRead(emailId) {
    try {
        const response = await apiRequest(`/api/emails/${emailId}/read`, {
            method: 'POST'
        });
        
        if (response && response.success) {
            showAlert(response.message, 'success');
            
            // 更新页面状态
            const statusBadge = document.querySelector('.badge.bg-primary');
            if (statusBadge && statusBadge.textContent.includes('未读')) {
                statusBadge.className = 'badge bg-success';
                statusBadge.innerHTML = '<i class="bi bi-envelope-open me-1"></i>已读';
            }
            
            // 移除标记已读按钮
            const markReadBtn = document.querySelector('button[onclick*="markAsRead"]');
            if (markReadBtn) {
                markReadBtn.remove();
            }
            
            // 更新未读数量
            if (typeof updateUnreadCount === 'function') {
                updateUnreadCount();
            }
        }
    } catch (error) {
        console.error('标记已读失败:', error);
        showAlert(error.message || '标记已读失败', 'danger');
    }
}

// 删除邮件
async function deleteEmail(emailId) {
    if (!confirm('确定要删除这封邮件吗？删除后将无法恢复。')) {
        return;
    }
    
    try {
        const response = await apiRequest(`/api/emails/${emailId}/delete`, {
            method: 'POST'
        });
        
        if (response && response.success) {
            showAlert(response.message, 'success');
            
            // 延迟跳转回列表页面
            setTimeout(() => {
                history.back();
            }, 1500);
        }
    } catch (error) {
        console.error('删除邮件失败:', error);
        showAlert(error.message || '删除邮件失败', 'danger');
    }
}

// 打印邮件
function printEmail() {
    try {
        const printWindow = window.open('', '_blank');
        if (!printWindow) {
            showAlert('无法打开打印窗口，请检查浏览器弹窗设置', 'warning');
            return;
        }
        
        const emailData = {
            subject: {{ email.subject|tojson }},
            senderUsername: {{ email.sender.username|tojson }},
            senderEmail: {{ email.sender.email|tojson }},
            recipientUsername: {{ email.recipient.username|tojson }},
            recipientEmail: {{ email.recipient.email|tojson }},
            sentAt: {{ email.sent_at.strftime('%Y年%m月%d日 %H:%M:%S')|tojson }},
            content: {{ email.content|tojson }}
        };
        
        const emailContent = `
            <!DOCTYPE html>
            <html>
            <head>
                <title>邮件打印 - ${emailData.subject}</title>
                <style>
                    body { font-family: Arial, sans-serif; margin: 20px; }
                    .header { border-bottom: 2px solid #ccc; padding-bottom: 10px; margin-bottom: 20px; }
                    .meta { margin-bottom: 10px; }
                    .content { line-height: 1.6; white-space: pre-wrap; }
                    .footer { margin-top: 30px; padding-top: 10px; border-top: 1px solid #ccc; font-size: 12px; color: #666; }
                </style>
            </head>
            <body>
                <div class="header">
                    <h2>${emailData.subject}</h2>
                </div>
                <div class="meta">
                    <p><strong>发件人：</strong>${emailData.senderUsername} (${emailData.senderEmail})</p>
                    <p><strong>收件人：</strong>${emailData.recipientUsername} (${emailData.recipientEmail})</p>
                    <p><strong>发送时间：</strong>${emailData.sentAt}</p>
                </div>
                <div class="content">${emailData.content}</div>
                <div class="footer">
                    <p>此邮件由邮箱演示系统生成，打印时间：${new Date().toLocaleString()}</p>
                </div>
            </body>
            </html>
        `;
        
        printWindow.document.write(emailContent);
        printWindow.document.close();
        printWindow.print();
    } catch (error) {
        console.error('打印邮件失败:', error);
        showAlert('打印邮件失败', 'danger');
    }
}

// 导出邮件
function exportEmail() {
    try {
        const emailData = {
            subject: {{ email.subject|tojson }},
            sender: {
                username: {{ email.sender.username|tojson }},
                email: {{ email.sender.email|tojson }}
            },
            recipient: {
                username: {{ email.recipient.username|tojson }},
                email: {{ email.recipient.email|tojson }}
            },
            sent_at: {{ email.sent_at.strftime('%Y-%m-%d %H:%M:%S')|tojson }},
            content: {{ email.content|tojson }},
            is_read: {{ email.is_read|tojson }}
        };
        
        const dataStr = JSON.stringify(emailData, null, 2);
        const dataBlob = new Blob([dataStr], {type: 'application/json'});
        
        const link = document.createElement('a');
        link.href = URL.createObjectURL(dataBlob);
        link.download = `email_${emailData.subject.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '_')}_{{ email.id }}.json`;
        link.click();
        
        // 清理对象URL
        setTimeout(() => {
            URL.revokeObjectURL(link.href);
        }, 100);
        
        showAlert('邮件已导出', 'success');
    } catch (error) {
        console.error('导出邮件失败:', error);
        showAlert('导出邮件失败', 'danger');
    }
}

// 页面加载完成后自动标记为已读（如果是收件人且未读）
document.addEventListener('DOMContentLoaded', function() {
    {% if email.recipient_id == current_user.id and not email.is_read %}
    // 延迟3秒后自动标记为已读
    setTimeout(() => {
        markAsRead({{ email.id }});
    }, 3000);
    {% endif %}
});

// 键盘快捷键
document.addEventListener('keydown', function(e) {
    // Ctrl/Cmd + R: 回复
    if ((e.ctrlKey || e.metaKey) && e.key === 'r') {
        e.preventDefault();
        {% if email.sender_id != current_user.id %}
            window.location.href = '{{ url_for("main.compose") }}?reply_to={{ email.id }}';
        {% endif %}
    }
    
    // Ctrl/Cmd + F: 转发
    if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
        e.preventDefault();
        window.location.href = '{{ url_for("main.compose") }}?forward={{ email.id }}';
    }
    
    // Delete: 删除
    if (e.key === 'Delete') {
        e.preventDefault();
        deleteEmail({{ email.id }});
    }
    
    // Escape: 返回
    if (e.key === 'Escape') {
        e.preventDefault();
        history.back();
    }
});
</script>
{% endblock %}